package org.colcon.web.model;

import java.util.HashMap;
import java.util.Map;

import org.colcon.web.model.framework.ICommand;
import org.colcon.web.server.Model;

public class Command extends Item implements ICommand
{
	public String getType(){return "command";}
	
	private static final long serialVersionUID = 954322162781977957L;
	
	protected static final String
	
		// arguments
		COMMAND = "command",
		ARGS = "args";
	
	public Command()
	{
		this(new HashMap<String, String>());
	}
	
	public Command(Map<String, String> args)
	{
		this(args.get(PARENT), args.get(ID), args.get(ARGS), args.get(COMMAND));
	}
	
	public Command(String parent, String id, String args, String command)
	{
		super(parent, id);
		
		if(!hasArg(PARENT))
			setArg(PARENT, "colcon/commands");
		
		setArg(ID, id);
		setArg(ARGS, args);
		setArg(COMMAND, command);
	}
	
	public String[] getArgs()
	{
		String args = getArg(ARGS);
		
		if(args == null || args.isEmpty())
			return new String[0];
		
		return args.split(" ");
	}
	
	public String getCommand()
	{
		return getArg(COMMAND);
	}
	
	public String getCommand(Map<String, String> args)
	{		
		if(getCommand() == null || args == null)
			return Model.NULL;

		String str = getCommand();
		
		for(String arg : getArgs())
		{
			String value = args.get(arg);
			
			if(value == null)
				return "null";
			
			value = value.trim();
			
			if(value.split(" ").length > 1)
				value = "{" + value + "}";
			
			str = str.replaceAll("\\[" + arg + "\\]", value);
		}
		
		return str;
	}
	
	public static String getCommandPath(String agent)
	{
		if(agent == null || agent.trim().length() == 0)
			return "colcon/commands";
		else
			return agent + "/commands";
	}
}
